<?php
/**
 *
 * @Author nikm $
 *
 * @Date 2011-12-28 $
 */

if(!defined('FROM_INDEX')) exit('Invalid request');

require ROOT_PATH.'include/lib/cache.func.php';
require ROOT_PATH.'include/lib/cookie.func.php';
require ROOT_PATH.'include/lib/session.func.php';
require ROOT_PATH.'include/lib/template.func.php';
require ROOT_PATH.'include/sql/sql_functions.php';
require_once ROOT_PATH.'include/function/form.func.php';

class masterObj
{
	var $request = array();
	//var $response = array();
	
	var $act = '';
	var $user = array();
	var $session = array();
	
	var $_is_messager = false;

	var $page_limit = '';
	var $page_num = '';
	
	var $ajhAuthKey = '';
	
	function __construct($request)
	{
		load_setting('config_global');
		
		$this->request = $request;
		$this->act = $request['act'];
		
		$this->page_limit = isset($this->request['count'])? min(500, max((int)$this->request['count'], 10)) : 10;
		$this->page_num = isset($request['page']) ? max(0, (int)$request['page'] - 1) : 0;
		
		$this->ajhAuthKey = md5(SEC_AUTHKEY.$_SERVER['HTTP_USER_AGENT'].'_IN_ADMIN_PANEL_'.date('Y-m-Y-m'));
		
/*
		$auth_code = cookie_get('auth');
		
		$password = $uid = '';
		if($auth_code)
		{
			list($password, $uid) = explode("\t", authcode($authcode, 'DECODE'));
		}
		
		$user = get_user($uid);
		if(isset($user['id']) && $user['id'] > 0)
		{
			$auth_code = authcode($user['password'].'\t'.$user['id'], 'ENCODE');
			cookie_set('auth', $auth_code);
			
			$this->user = $user;
		}
		else
		{
			$this->user['id'] = -1;
			$this->user['name'] = 'guest';
			$this->user['group_id'] = -1;
			
			cookie_delete('auth');
			
			//TODO, for test
			//$this->messager("Please <a href='admin.php?m=login'>login</a> first.", null);
		}
*/
		
		if($this->request['mod'] != 'login')
		{
			unset($ajhAuth, $_pwd, $_uid);
			if(($ajhAuth = cookie_get('ajhAuth')))
			{
				list($_pwd, $_uid) = explode("\t", authcode($ajhAuth, 'DECODE', $this->ajhAuthKey));
			}
			
			$user = get_user($_uid);
	
			if (!$ajhAuth || !$_pwd || ($_pwd != $user['password']) || ($_uid < 1) || ($_uid != $user['id']))
			{
				$this->Messager(null, 'admin.php?m=login');
			}
					
			$this->user = $user;
		}
		
		$this->_checkUser();
		
		$this->updateSession();
	}

	function showBody($body)
	{
		echo $body;
		
		$this->updateSession();
		if($this->request['mod'] != 'index' || isset($this->request['action_name']))$this->showFooter();
	}
	
	function showHeader($title, $additional_file_list=array(), $additional_str="", $sub_menu_list=array(), $header_menu_list=array())
	{
		include template('admin/header');
	}
	
	function showFooter()
	{
		include template('admin/footer');
	}
	
	function copyRight()
	{
		$year = date('Y');
		echo '<div style="clear:both;text-align:center;margin:5px auto;">Copyright&copy; '.$year.', nikm</div>';
	}
	
	function actionName()
	{
		$action_name = isset($this->request['action_name']) ? trim($this->request['action_name']) : '';
		
		if(!empty($action_name))return $action_name;
		
		include  ROOT_PATH.'config/menu_list_admin.php';
		foreach($menu_list as $_menu_list)
		{
			if(!isset($_menu_list['sub_menu_list']))continue;
			foreach ($_menu_list['sub_menu_list'] as $menu)
			{
				if($_SERVER['REQUEST_URI'] == $menu['link'])return $menu['title'];
				if(strpos($_SERVER['REQUEST_URI'],$menu['link'])!==false)
				{
					$action_name = $menu['title'];
				}
			}
		}
		return $action_name;
	}
	
	function messager($message, $redirect_to='', $time=2, $return_msg=false, $js=null)
	{
		$this->_is_messager = true;
		
		$to_title = ($redirect_to === '' || $redirect_to == -1) ? "返回上一页" : "跳转到指定页面";
		
		if($redirect_to === null)
		{
			$return_msg = ($return_msg === false) ? "&nbsp;" : $return_msg;
		}
		else
		{
			$redirect_to = ($redirect_to !== '') ? $redirect_to : ($from_referer = referer());
			
			if(is_numeric($redirect_to) !== false && $redirect_to !== 0)
			{
				if($time !== null)
				{
					$url_redirect = "<script type=\"text/javascript\">\r\n";
					$url_redirect .= sprintf("window.setTimeout(\"history.go(%s)\",%s);\r\n", $redirect_to, $time*1000);
					$url_redirect .= "</script>\r\n";
				}
				
				$redirect_to = "javascript:history.go({$redirect_to})";
			}
			else
			{
				if($message === null)
				{
					$redirect_to = rawurldecode(stripslashes(($redirect_to)));
					@header("Location: $redirect_to"); #HEADER跳转
				}
				if($time !== null)
				{
					$url_redirect = $redirect_to ? '<meta http-equiv="refresh" content="'.$time.'; URL='.$redirect_to.'">' : null;
				}
			}
		}
		
		$title = "消息提示:".(is_array($message) ? implode(',', $message) : $message);

		$title = strip_tags($title);
		if($js != '')$js = "<script type=\"text/javascript\">{$js}</script>";

		ob_start();
		$this->showHeader($title);
		include_once template('admin/messager');
		$body = ob_get_clean();

		$this->showBody($body);
		exit;
	}
	
	function updateSession()
	{
		$sid = cookie_get('sid');
		$session = session_get($sid);
		
		if(check_array($session))
		{
			$this->session = $session;
		}
		else
		{
			$this->session = session_init($sid);
		}
		
		$this->session['uid'] = $this->user['id'];
		$this->session['user_name'] = $this->user['name'];
		$this->session['group_id'] = $this->user['group_id'];
		$this->session['ip'] = client_ip();
		
		session_update($this->session);
	}
	
	/**
	 * 
	 * Check if user login & has permission
	 */
	private function _checkUser()
	{
		//TODO
		return true;
	}
	
	/**
	 * 
	 * Get user info by uid, if uid is null, return current user
	 * 
	 * @param string $uid
	 * 
	 * @return array $user
	 */
	function _user($uid='')
	{
		return $uid ? get_user($uid) : $this->user;	
	}
}